from typing import Callable, Optional
import shutil
import os
from server.login import User
from server import vfs
import asyncio
from . import vos

# 同 vos


async def mkthread(func, *args, **kwargs):
    def new_thread():
        try:
            return func(*args, **kwargs)
        except Exception as e:
            return e
    ret = await asyncio.to_thread(new_thread)
    if (isinstance(ret, Exception)):
        raise ret
    return ret


def fix(func):
    def warpper(self, *args, **kwargs):
        return func(*args, **kwargs)
    return warpper


class Shutil():
    """Utility functions for copying and archiving files and directory trees.

    XXX The functions here don't copy the resource fork or other metadata on Mac.

    """

    def __init__(self, user: User):
        self.user = user

    async def copy(self, src: str, dst: str, *, follow_symlinks: bool = True) -> str:
        """Copy data and mode bits ("cp src dst"). Return the file's destination.

        The destination may be a directory.

        If follow_symlinks is false, symlinks won't be followed. This
        resembles GNU's "cp -P src dst".

        If source and destination are the same file, a SameFileError will be
        raised.

        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copy, src, dst, follow_symlinks=follow_symlinks)

    async def copy2(self, src: str, dst: str, *, follow_symlinks: bool = True) -> str:
        """Copy data and metadata. Return the file's destination.

        Metadata is copied with copystat(). Please see the copystat function
        for more information.

        The destination may be a directory.

        If follow_symlinks is false, symlinks won't be followed. This
        resembles GNU's "cp -P src dst".
        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copy2, src, dst, follow_symlinks=follow_symlinks)

    async def copyfileobj(self, fsrc: str, fdst: str, length: int = 0) -> None:
        """copy data from file-like object fsrc to file-like object fdst"""
        ret = await vfs.get_permission(self.user.username, os.path.abspath(fsrc))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(fdst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copyfileobj, fsrc, fdst, length=length)

    async def copymode(self, src: str, dst: str, *, follow_symlinks: bool = True) -> None:
        """Copy mode bits from src to dst.

        If follow_symlinks is not set, symlinks aren't followed if and only
        if both `src` and `dst` are symlinks.  If `lchmod` isn't available
        (e.g. Linux) this method does nothing.

        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copymode, src, dst, follow_symlinks=follow_symlinks)

    async def copystat(self, src, dst, *, follow_symlinks=True) -> None:
        """Copy file metadata

        Copy the permission bits, last access time, last modification time, and
        flags from `src` to `dst`. On Linux, copystat() also copies the "extended
        attributes" where possible. The file contents, owner, and group are
        unaffected. `src` and `dst` are path-like objects or path names given as
        strings.

        If the optional flag `follow_symlinks` is not set, symlinks aren't
        followed if and only if both `src` and `dst` are symlinks.
        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copystat, src, dst, follow_symlinks=follow_symlinks)

    async def move(self, src: str, dst: str, *, copy_function=shutil.copy2) -> str:
        """Recursively move a file or directory to another location. This is
        similar to the Unix "mv" command. Return the file or directory's
        destination.

        If dst is an existing directory or a symlink to a directory, then src is
        moved inside that directory. The destination path in that directory must
        not already exist.

        If dst already exists but is not a directory, it may be overwritten
        depending on os.rename() semantics.

        If the destination is on our current filesystem, then rename() is used.
        Otherwise, src is copied to the destination and then removed. Symlinks are
        recreated under the new name if os.rename() fails because of cross
        filesystem renames.

        The optional `copy_function` argument is a callable that will be used
        to copy the source or it will be delegated to `copytree`.
        By default, copy2() is used, but any function that supports the same
        signature (like copy()) can be used.

        A lot more could be done here...  A look at a mv.c shows a lot of
        the issues this implementation glosses over.

        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.move, src, dst, copy_function=copy_function)

    async def copytree(self, src: str, dst: str, symlinks: bool = False, ignore=None, dirs_exist_ok: bool = False) -> str:
        """Recursively copy a directory tree and return the destination directory.

        If exception(s) occur, an Error is raised with a list of reasons.

        If the optional symlinks flag is true, symbolic links in the
        source tree result in symbolic links in the destination tree; if
        it is false, the contents of the files pointed to by symbolic
        links are copied. If the file pointed to by the symlink doesn't
        exist, an exception will be added in the list of errors raised in
        an Error exception at the end of the copy process.

        You can set the optional ignore_dangling_symlinks flag to true if you
        want to silence this exception. Notice that this has no effect on
        platforms that don't support os.symlink.

        The optional ignore argument is a callable. If given, it
        is called with the `src` parameter, which is the directory
        being visited by copytree(), and `names` which is the list of
        `src` contents, as returned by os.listdir():

            callable(src, names) -> ignored_names

        Since copytree() is called recursively, the callable will be
        called once for each directory that is copied. It returns a
        list of names relative to the `src` directory that should
        not be copied.

        The optional copy_function argument is a callable that will be used
        to copy each file. It will be called with the source path and the
        destination path as arguments. By default, copy2() is used, but any
        function that supports the same signature (like copy()) can be used.

        If dirs_exist_ok is false (the default) and `dst` already exists, a
        `FileExistsError` is raised. If `dirs_exist_ok` is true, the copying
        operation will continue if it encounters existing directories, and files
        within the `dst` tree will be overwritten by corresponding files from the
        `src` tree.
        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(src))
        if (ret < 1):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(dst))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.copytree, src, dst, symlinks, ignore, dirs_exist_ok=dirs_exist_ok)

    async def rmtree(self, path: str, ignore_errors: bool = False) -> None:
        """_RmtreeType"""
        ret = await vfs.get_permission(self.user.username, os.path.abspath(path))
        if (ret < 2):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.rmtree.__call__, path, ignore_errors)

    async def disk_usage(self, path: str) -> shutil._ntuple_diskusage:
        """Return disk usage statistics about the given path.

        Returned value is a named tuple with attributes 'total', 'used' and
        'free', which are the amount of total, used and free space, in bytes.
        """
        ret = await vfs.get_permission(self.user.username, os.path.abspath(path))
        if (ret < 1):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.disk_usage, path)

    async def make_archive(self, base_name: str, format: str, root_dir: Optional[str] = None, base_dir: Optional[str] = None, verbose: bool = False, dry_run: bool = False, owner: Optional[str] = None, group: Optional[str] = None, logger: Optional[Callable[..., None]] = None) -> str:
        """Create an archive file (eg. zip or tar).

        'base_name' is the name of the file to create, minus any format-specific
        extension; 'format' is the archive format: one of "zip", "tar", "gztar",
        "bztar", or "xztar".  Or any other registered format.

        'root_dir' is a directory that will be the root directory of the
        archive; ie. we typically chdir into 'root_dir' before creating the
        archive.  'base_dir' is the directory where we start archiving from;
        ie. 'base_dir' will be the common prefix of all files and
        directories in the archive.  'root_dir' and 'base_dir' both default
        to the current directory.  Returns the name of the archive file.

        'owner' and 'group' are used when creating a tar archive. By default,
        uses the current owner and group.
        """
        if (root_dir == None):
            root_dir = await vos.OS(self.user).path.getcwd()
        ret = await vfs.get_permission(self.user.username, os.path.abspath(base_name))
        if (ret < 2):
            raise PermissionError("Permission denied")
        ret = await vfs.get_permission(self.user.username, os.path.abspath(root_dir))
        if (ret < 1):
            raise PermissionError("Permission denied")
        return await mkthread(shutil.make_archive, base_name, format, root_dir, base_dir, verbose, dry_run, owner, group, logger)
